package com.loveyukari.Interceptor;

import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.loveyukari.model.ManageAuth;
import com.loveyukari.service.ManagerService;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.loveyukari.service.IpService;

/**
*
*yangshaohua
*2016年9月2日上午10:34:37
**/
@Component
public class IpInterceptor implements HandlerInterceptor{

	
	
	@Autowired
	private IpService ipService;
	@Autowired
	private ManagerService managerService;


	private String REQUEST_TIME = "REQUEST_TIME";
	
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String ip = request.getHeader("X-Real-IP");
		if (StringUtils.isBlank(ip)){
			ip = request.getRemoteAddr();
		}
		if (ipService.isBlackIp(ip)){
			return false;
		}
		String requestPath = request.getServletPath();
		if (ipService.isLoginRequest(requestPath) && ipService.isNotLogin()){
			return false;
		}
		Map map = request.getParameterMap();
		JSONObject json = JSONObject.fromObject(map);
		Cookie[] cookies = request.getCookies();
		if (cookies != null){
			for (int i = 0; i < cookies.length; i++) {
				Cookie cookie = cookies[i];
				if (cookie.getName().equals("MANAGE_SIGN")){
					String sign = cookie.getValue();
					if (StringUtils.isNotBlank(sign)){
						request.setAttribute("sign",sign);
						ManageAuth manageAuth = managerService.getManageAuthBySign(sign);
						json.put("auth",manageAuth);
					}
				}
			}
		}
		ipService.recordIPRequest(ip, requestPath,json);
		return true;
	}
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}
	

}
